package io.alvin.ch02;

import java.util.HashMap;
import java.util.Map;

/**
 * 多线程下的HashMap错误
 * 期望输出：1_000_000
 *
 * 实际输出：可能小于这个值，或程序无法结束（JDK8不会死循环）
 *
 * Created by Alvin on 2017/7/7.
 */
public class HashMapMultiThread {

    static Map<String, String> map = new HashMap<String, String>();

    public static class AddThread implements Runnable {
        int start = 0;
        public AddThread(int start) {
            this.start = start;
        }

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            for (int i = 0; i < 1_000_000; i += 2) {
                map.put(Integer.toString(i), Integer.toBinaryString(i));
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new HashMapMultiThread.AddThread(0));
        Thread t2 = new Thread(new HashMapMultiThread.AddThread(1));
        t1.start();
        t2.start();
        t1.join(); t2.join();
        System.out.println(map.size());
    }
}
